package com.guyu.common.core.validator.constraintvalidators;

import com.guyu.common.core.validator.constraints.RegexMatch;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import org.apache.commons.lang3.StringUtils;

import java.util.regex.Pattern;


/**
 * <p> 校验输入字符串是否匹配正则表达式 </p>
 */
public class RegexMatchValidatorImpl implements ConstraintValidator<RegexMatch, String> {

    private String regex;

    @Override
    public void initialize(RegexMatch constraintAnnotation) {
        //传入value 值，可以在校验中使用
        this.regex = constraintAnnotation.regex();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (StringUtils.isBlank(value)) {
            return true;
        }
        Pattern pattern = Pattern.compile(regex);
        return pattern.matcher(value.trim()).matches();
    }
}
